layui.use(['element', 'layer', 'jquery', 'layedit', 'form', 'laypage'], function () {
    var element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    var layedit = layui.layedit;
    var form = layui.form;
    var laypage = layui.laypage
        , layer = layui.layer;

    //监听导航点击，解决导航栏有时候不显示的bug
    element.on('nav(demo)', function(elem){
    });

    var index = layedit.build('edit', {
        tool: ['strong', 'italic', 'face']
        , height: 150
    })

    $('#submitBtn').click(function () {
        //获取编辑器的值
        var content = layedit.getContent(index);
        alert(content);
    });

    window.reply_function = function (username) {
        $(".layui-form").css("display", "block");
        $("#submitBtn").css("display", "");
        layedit.setContent(index, "回复@" + username + ":&nbsp;");
    }

    //该文章一共有多少张图片
    // var imgCount = $(".article-content img").length;
    // $(".article-content img").each(function (i,e) {
    //     $(this).click(function () {
    //         handleImg(this,i,imgCount);
    //     });
    // });


    $('#sumbitping').click(function () {

        //必填
        var articleId = $("#id").val();
        var userName = $("#userName").val();
        var email = $("#email").val();
        var content = $("#txaArticle").val();

        //可选
        var url = $("#url").val();
        var replyForId = $("#replyForId").val();
        var replyForName = $("#replyForName").val();

        if(articleId == null || articleId == '' || articleId == undefined ||
            userName == null || userName == '' || userName == undefined ||
            email == null || email == '' || email == undefined ||
            content == null || content == '' || content == undefined){
            layer.msg("填写完整信息再提交！");
            return;
        }

        if( url != null && url != '' && url != undefined ){

            if(url.indexOf("https:") == -1 && url.indexOf("http:") == -1){
                layer.msg("网址要以http或者https开头");
                return;
            }
        }

        $.ajax({
            type:"POST"
            ,url:"/article/saveComment"
            ,data:{
                "articleId":articleId,
                "userName":userName,
                "email":email,
                "content":content,
                "url":url,
                "replyForId":replyForId,
                "replyForName":replyForName
            }
            ,success:function (res) {
                $("#frmSumbit")[0].reset();
                layer.msg(res.message);
            }
            ,error:function () {
                alert("服务器错误！");
            }
        });


    });

});

$(function () {
    //判断是网赚资讯的文章详情还是每日一赚的文章详情
    var typeId = $("#type").val();
    /**
     * 导航栏菜单高亮显示
     */
    $("#menu" + typeId).css("color", "#45B6F7");
    $("#menu" + typeId).addClass("layui-this");

    //隐藏评论框和按钮
    $(".layui-form").css("display", "none");
    $("#submitBtn").css("display", "none");

    $("#currenUrl").text(window.location.href);

    $(".pay_item").click(function () {
        $(this).addClass('checked').siblings('.pay_item').removeClass('checked');
        var dataid = $(this).attr('data-id');
        $(".shang_payimg img").attr("src", "/img/dashang/" + dataid + "img.png");
        $("#shang_pay_txt").text(dataid == "alipay" ? "支付宝" : "微信");
    });

    var articleId = $("#id").val();
    var likes = window.localStorage.getItem("likes");
    likes = JSON.parse(likes);
    if(likes != null && likes.indexOf(articleId) != -1){
        //已经点过赞，设置为点赞状态
        $(".like_circle").addClass("liked");
    }
    var dips = window.localStorage.getItem("dips");
    dips = JSON.parse(dips);
    if(dips != null && dips.indexOf(articleId) != -1){
        //已经点过赞，设置为点赞状态
        $(".dip_circle").addClass("liked");
    }

    var projectId = $("#id").val();
    var reads = window.localStorage.getItem("reads");
    reads = JSON.parse(reads);
    if(reads == null){
        reads = [];
        reads.push(projectId);
        window.localStorage.setItem("reads",JSON.stringify(reads));
        readCount(projectId);
    }else{
        if(reads.indexOf(projectId) == -1){
            //没有阅读过，阅读量+1
            reads.push(projectId);
            window.localStorage.setItem("reads",JSON.stringify(reads));
            readCount(projectId);
        }
    }


})

function readCount(projectId){
    //保存项目
    $.ajax({
        url:"/article/updateCount",
        type:"POST",
        data: {
            projectId:projectId
        },
        // contentType:"application/json;charset=utf-8",
        success:function (result) {

        },
        error:function (res) {
            console.log(res);
        }
    });
}

function dashangToggle() {
    $(".hide_box").fadeToggle();
    $(".shang_box").fadeToggle();
}

function articleDip(){
    var articleId = $("#id").val();
    var hasClass = $(".dip_circle").hasClass("liked");
    if(hasClass){
        layer.msg('<span style="color: white">您已经踩过啦!</span>', {
            time: 3000, //20s后自动关闭
        });
    }else{
        //点赞
        $(".dip_circle").addClass("liked");
        var count = $("#dipCount").text();
        $("#dipCount").text(parseInt(count)+1)
        var dips = window.localStorage.getItem("dips");
        dips = JSON.parse(dips);
        if(dips == null){
            dips = [];
            dips.push(articleId);
            window.localStorage.setItem("dips",JSON.stringify(dips));
            addDip(articleId);
        }else{
            if(dips.indexOf(articleId) == -1){
                //踩数+1
                dips.push(articleId);
                window.localStorage.setItem("dips",JSON.stringify(dips));
                addDip(articleId);
            }
        }
    }
}

function articleLike(){
    var articleId = $("#id").val();
    var hasClass = $(".like_circle").hasClass("liked");
    if(hasClass){
        layer.msg('<span style="color: white">您已经点过赞啦!</span>', {
            time: 3000, //20s后自动关闭
        });
    }else{
        //点赞
        $(".like_circle").addClass("liked");
        var count = $("#likeCount").text();
        $("#likeCount").text(parseInt(count)+1)
        var likes = window.localStorage.getItem("likes");
        likes = JSON.parse(likes);
        if(likes == null){
            likes = [];
            likes.push(articleId);
            window.localStorage.setItem("likes",JSON.stringify(likes));
            addLike(articleId);
        }else{
            if(likes.indexOf(articleId) == -1){
                //点赞数+1
                likes.push(articleId);
                window.localStorage.setItem("likes",JSON.stringify(likes));
                addLike(articleId);
            }
        }
    }

}

function addLike(id){
    //保存项目
    $.ajax({
        url:"/article/like",
        type:"POST",
        data: {
            id:id
        },
        // contentType:"application/json;charset=utf-8",
        success:function (result) {

        },
        error:function (res) {
            console.log(res);
            $(".like_circle").removeClass("liked");
            var count = $("#likeCount").text();
            $("#likeCount").text(parseInt(count)-1)
        }
    });
}

function addDip(id){
    //保存项目
    $.ajax({
        url:"/article/dip",
        type:"POST",
        data: {
            id:id
        },
        // contentType:"application/json;charset=utf-8",
        success:function (result) {

        },
        error:function (res) {
            console.log(res);
            $(".dip_circle").removeClass("liked");
            var count = $("#dipCount").text();
            $("#dipCount").text(parseInt(count)-1)
        }
    });
}


function shareSina(){
    var c = window.location.href;
    var e = $("#imgList").val();
    if (e == null || e == undefined || e == '') {
        e = '';
    }
    var d = $("#showSinaSummary").val();
    var url = "//service.weibo.com/share/share.php?title\x3d" + encodeURIComponent(d + "\u9605\u8bfb\u8be6\u60c5：" + c) + "\x26pic\x3d" + e + "&appkey=1891775722&searchPic=true";
    window.open(url);
}

function reply(id,userName) {
    $("#replyForId").val(id);
    $("#replyForName").val(userName);

    $("#txaArticle").attr("placeholder","@"+userName+"：")

}


function handleImg(e,i,count) {
    if($(".opacityBottom")){
        $(".opacityBottom").remove()
    }

    var imgsrc = e.src;
    //获取图片路径
    var opacityBottom = '<div class="opacityBottom" style = "display:none;">' +
        '<input  data-id="'+i+'"  class="bigImg preBtn" type="button" value="<" />' +
        '<img  class="bigImg" id="showImg" src="' + imgsrc + '">' +
        '<input data-id="'+i+'"  class="bigImg nexBtn" type="button" value=">" />' +
        '</div>';
    $(document.body).append(opacityBottom);
    //变大函数
    toBigImg(i,count);

    //变大后图片的高度
    var largeHeight = $(".bigImg")[1].scrollHeight;
    var largeWidth = $(".bigImg")[1].scrollWidth;
    var height;
    if(largeHeight+60 > document.body.clientHeight){
        $("img.bigImg").css("height",document.body.clientHeight-80+"px")
    }
    if(largeWidth>document.body.clientWidth){
        $("img.bigImg").css("width",document.body.clientWidth)
    }
    if(document.body.clientWidth < 768){
        height = ($(".bigImg")[1].scrollHeight/2);
    }else{
        height = ($(".bigImg")[1].height/2);
    }


    var screenWidht = document.body.clientWidth/2;
    var screenHeight = document.body.clientHeight/2;
    //箭头图标的高度
    var height_total = screenHeight + height + 20;
    //左箭头图标的宽度
    var width_total = screenWidht - 30;
    //右箭头图标的宽度
    var width_total2 = screenWidht + 30;

    $(".preBtn").css("left",width_total+"px");
    $(".preBtn").css("top",height_total+"px");
    $(".preBtn").css("width","40px");
    $(".preBtn").css("height","20px");

    $(".nexBtn").css("left",width_total2+"px");
    $(".nexBtn").css("top",height_total+"px");
    $(".nexBtn").css("width","40px");
    $(".nexBtn").css("height","20px");

    //图片左右滑动
    changeImg(i,count,$(".article-content img"));
}

//放大图片
function toBigImg(i,count) {

        $(".opacityBottom").addClass("opacityBottom");//添加遮罩层
        $(".opacityBottom").show();
        $("html,body").addClass("none-scroll");//下层不可滑动
        $(".bigImg").addClass("bigImg");//添加图片样式

    $(".opacityBottom").click(function () {//点击关闭
        $("html,body").removeClass("none-scroll");
        $(".opacityBottom").remove();
    });
};

function changeImg(i,count,imgs) {
    // $("html,body").removeClass("none-scroll");
    // $(".opacityBottom").remove();

    var pre;
    var next;
    if(i == 0){
        pre = count - 1;
    }else{
        pre = i - 1;
    }
    if(i == (count-1)){
        next = 0;
    }else{
        next = i + 1;
    }
    //前一张
    $(".preBtn").click(function () {
        handleImg(imgs[pre],pre,count);
    })
    //后一张
    $(".nexBtn").click(function () {
        handleImg(imgs[next],next,count);
    });

    $(".closeBtn").click(function () {
            $("html,body").removeClass("none-scroll");
            $(".opacityBottom").remove();
    })

}

function QQGroup() {
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['220px', '120px'], //宽高
        content: '<div class="layui-row" style="margin: 20px 10px">QQ群：883431963<a class="layui-btn layui-btn-normal layui-btn-xs" onclick="openQQGroup()" style="margin-left: 10px">点我进群</a></div>'
    });
}

function openQQGroup(){
    window.open("https://qm.qq.com/cgi-bin/qm/qr?k=FSCr69W81qkd_ezJMDosxjgxK5rMb8oL&jump_from=webapi&authKey=i+oLLsOyBmEm0mTCuLbLVYeDCvR5CQ8tCQRJLqK4Q91cVUOn3YIfw3C2/adUVYw7","_black");
}

function QQGroup2() {
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['220px', '120px'], //宽高
        content: '<div class="layui-row" style="margin: 20px 10px">QQ群：916063529<a class="layui-btn layui-btn-normal layui-btn-xs" onclick="openQQGroup2()" style="margin-left: 10px">点我进群</a></div>'
    });
}

function openQQGroup2() {
    window.open("//shang.qq.com/wpa/qunwpa?idkey=730e04cd5c2db9a289ed7b6ea9d2891e5baeee8017e63f80d494b9b1ba4886e5","_black");
}

